package com.lemon.smartsafety.listener;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * Created by Cooliean on 16/1/17.
 */
public class RecyclerViewLoadMoreListener extends RecyclerView.OnScrollListener{
    private LinearLayoutManager linearLayoutManager;
    private OnLoadMoreListener onLoadMoreListener;
    private int limit;

    /**
     * 是否能加载更多
     */
    private boolean hasMore = true;
    /**
     * 是否正在加载
     */
    private boolean isLoading = false;


    /**
     * 加载更多的坚挺
     * @param linearLayoutManager 排版方式
     * @param onLoadMoreListener
     * @param limit 要比limit个项目多的请求才能满足请求更多的条件
     */
    public RecyclerViewLoadMoreListener(@NonNull LinearLayoutManager linearLayoutManager, @NonNull OnLoadMoreListener onLoadMoreListener, int limit) {
        super();
        this.linearLayoutManager = linearLayoutManager;
        this.onLoadMoreListener = onLoadMoreListener;
        this.limit = limit;
    }
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        if (hasMore && isLoading && linearLayoutManager.getItemCount() >= limit
                && linearLayoutManager.findLastVisibleItemPosition() == linearLayoutManager.getItemCount() - 1)
        { // 向下滑动，判断最后一个item是不是显示中
            onLoadMoreListener.onLoadMore();
        }
    }
    public interface OnLoadMoreListener {
        void onLoadMore();
    }

    public boolean isHasMore() {
        return hasMore;
    }

    public void setHasMore(boolean hasMore) {
        this.hasMore = hasMore;
    }

    public boolean isLoading() {
        return isLoading;
    }

    public void setLoading(boolean loading) {
        isLoading = loading;
    }
}
